package com.worksystem.Dao;

import java.io.Serializable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Query;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.worksystem.entity.Grade;
import com.worksystem.entity.Student;
import com.worksystem.entity.Subject;
import com.worksystem.entity.Test;
import com.worksystem.util.SqlHandle;

@SuppressWarnings("unchecked")
@Component("testDao")
public class TestDaoImp extends BaseDao<Test> implements TestDao {
	
	public TestDaoImp() {
		super(Test.class);
	}

	@Autowired 
	public  HttpServletRequest requst;
	
	@Override
	public Object postteststograde(String testjson,Integer uid,Integer subjectid,String time){
		//tests中每个对象属性：tid:题目编号 answer:答案编号，题目分值 grade:每一道题的分值
		Query query1=getSession().createSQLQuery("select t.id ,t.ANSWERID  from test as t where t.SID="+subjectid);
		List<Object[]> datatests=query1.list();
		System.out.println(datatests);
		JSONArray tests=new JSONArray(testjson);
		float score=0;
		for (int i = 0; i < datatests.size(); i++) {
			JSONObject test=tests.getJSONObject(i);
			Object[] datatest=datatests.get(i);
			//如果用户提交的答案和原来题库的答案相等
			System.out.println(test.get("answer")+"++++++"+datatest[1]);
			if(Integer.parseInt(test.get("answer").toString())==Integer.parseInt(datatest[1].toString())){
				score+=test.getDouble("grade");
			}
		}
		//成绩核算完毕接下来提交至数据库
		Student student=(Student) getSession().createQuery("from Student where uid=:uid").setParameter("uid", uid).uniqueResult();
		System.out.println(student);
		Subject subject=(Subject) getSession().get(Subject.class, subjectid);
		Grade grade=new Grade();
		grade.setScore(score);
		grade.setTime(time);
		grade.setStudent(student);
		grade.setSubject(subject);
		try {
			getSession().save(grade);
			return "1";
		} catch (Exception e) {
			return "0";
		}
	}
	@Override
	public boolean deleteByPK(Serializable... id) {
		SqlHandle handle = new SqlHandle(SqlHandle.OPERATES[3],"answer");
		handle.CONDITION("testid", "in", id);
		System.out.println("删除方法deleteByPK执行.sql:"+handle.toString());
		getSession().createSQLQuery(handle.toString()).executeUpdate();
		SqlHandle testhandle = new SqlHandle(SqlHandle.OPERATES[3],"test");
		testhandle.CONDITION("id", "in", id);
		System.out.println("删除方法deleteByPK执行.sql:"+testhandle.toString());
		int num =getSession().createSQLQuery(testhandle.toString()).executeUpdate();
		if(num>0)
		return true;
		else
		return false;
	}
	
}
